package cn.wch.ch934xlib.chip;

import android.hardware.usb.UsbDeviceConnection;


import androidx.annotation.NonNull;

;import static cn.wch.ch934xlib.chip.ChipTransferUtil.cmdOut;
import static cn.wch.ch934xlib.chip.ChipTransferUtil.controlIn;

public class ChipInitUtil {

    private static byte VENDOR_WRITE_REG_TYPE=(byte) 0xC0;
    private static byte REG_IER=0x01;
    private static byte REG_IIR=0x02;
    private static byte REG_LCR=0x03;
    private static byte REG_MCR=0x04;
    private static byte REG_MSR=0x06;

    public static boolean initChip(@NonNull ChipEntity chipEntity,@NonNull UsbDeviceConnection connection,int serialCount,boolean support9Line){
        int ret=0;
        if(serialCount==4 || serialCount==2) {
            for (int i = 0; i < serialCount; i++) {
                int request = VENDOR_WRITE_REG_TYPE;
                int addr = 0x10 * i + 0x08;

                int b1= request;
                int b2= addr+REG_IIR;
                int b3= 0x87;

                ret = cmdOut(connection,chipEntity.getCtrlEpOut(),b1, b2, b3);
                if (ret < 0)
                    return false;
                b2= addr+REG_LCR;
                b3= 0x03;
                ret = cmdOut(connection,chipEntity.getCtrlEpOut(),b1, b2, b3);
                if (ret < 0)
                    return false;
                b2= addr+REG_IER;
                if(support9Line){
                    b3= 0x0F;
                }else {
                    b3= 0x07;
                }
                ret = cmdOut(connection,chipEntity.getCtrlEpOut(), b1, b2, b3);
                if (ret < 0)
                    return false;
                b2= addr+REG_MCR;
                b3= 0x08;
                ret = cmdOut(connection,chipEntity.getCtrlEpOut(), b1, b2, b3);
                if (ret < 0)
                    return false;
            }
        }else {
            return false;
        }
        return true;
    }

    public static ChipFeature getChipFeature(@NonNull UsbDeviceConnection connection){

        byte[] buffer = new byte[4];

        int ret  = controlIn(connection, ChipTransferUtil.UsbCmd.USB_VEN_READ_VER, 0x0000, 0x0000, buffer, 0x0004);
        if (ret<0) {
            return null;
        }
        ChipFeature feature=new ChipFeature();
        int serialCount = buffer[1] & 0x3f;
        feature.setSerialCount(serialCount);

        if((buffer[1] & (0x01<<6))!=0x00){
            feature.setSupportMode9Line(true);
        }else {
            feature.setSupportMode9Line(false);
        }
        return feature;
    }







}
